import json
import os
import math
import numpy as np

def lon_to_x(lon, zoom):
    """经度转换为像素 X 坐标"""
    return ((lon + 180) / 360) * math.pow(2, zoom) * 256

def lat_to_y(lat, zoom):
    """纬度转换为像素 Y 坐标"""
    sin_lat = math.sin(lat * math.pi / 180)
    y = 0.5 - math.log((1 + sin_lat) / (1 - sin_lat)) / (4 * math.pi)
    return y * math.pow(2, zoom) * 256

def calculate_image_size(geojson_path, zoom):
    """计算指定缩放级别下覆盖区域所需的图片像素大小"""
    try:
        # 读取 GeoJSON 文件
        with open(geojson_path, 'r', encoding='utf-8') as f:
            data = json.load(f)

        # 提取所有坐标点
        coordinates = []
        for feature in data['features']:
            if feature['geometry']['type'] == 'Polygon':
                coords = feature['geometry']['coordinates'][0]
                coordinates.extend(coords)
            elif feature['geometry']['type'] == 'MultiPolygon':
                for polygon in feature['geometry']['coordinates']:
                    coordinates.extend(polygon[0])

        # 转换为 numpy 数组便于计算
        coords_array = np.array(coordinates)
        
        # 获取经纬度范围
        min_lon, max_lon = np.min(coords_array[:, 0]), np.max(coords_array[:, 0])
        min_lat, max_lat = np.min(coords_array[:, 1]), np.max(coords_array[:, 1])

        # 计算四个角点的像素坐标
        x1, y1 = lon_to_x(min_lon, zoom), lat_to_y(max_lat, zoom)  # 左上
        x2, y2 = lon_to_x(max_lon, zoom), lat_to_y(min_lat, zoom)  # 右下

        # 计算像素尺寸
        width = int(math.ceil(x2 - x1))
        height = int(math.ceil(y2 - y1))

        print(f"\n在缩放级别 {zoom} 下:")
        print(f"建议图片尺寸: {width} x {height} 像素")
        print(f"覆盖经纬度范围: 经度 [{min_lon:.6f}, {max_lon:.6f}], 纬度 [{min_lat:.6f}, {max_lat:.6f}]")
        
        return width, height

    except Exception as e:
        print(f"计算过程中发生错误: {str(e)}")
        return None, None

if __name__ == '__main__':
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    geojson_path = os.path.join(current_dir, 'geojson', 'sz_fill.json')
    
    # 计算 zoom 9 级别下的像素尺寸
    zoom = 9
    width, height = calculate_image_size(geojson_path, zoom)